<?php

namespace core;

use Exception;

class Template
{
    public static function get_view_app() {

        // 尝试从URL获取view_app
        $url = str_replace('', '', current_url());
        $url = filter_var($url, FILTER_SANITIZE_URL);
        $url_bits = explode('/', $url);

        if (empty($url_bits[3])) {
            $view_app = APP_NAME;
        } else {
            $view_app = $url_bits[3];
        }

        return $view_app;
    }

    public static function display($data=null) {

        if (!isset($data['view_app'])) {
            $data['view_app'] = self::get_view_app();
        }

        if (!isset($data['view_file'])) {
            $data['view_file'] = 'index';
        }

        $file_path = APP_PATH . $data['view_app'] . '/view/' . $data['view_file'] . '.php';
        self::attempt_include($file_path, $data);
    }

    public static function load($file_name, $data=null) {
        $file_path = ROOT_PATH.'template/' . config('theme') . '/' . $file_name.'.php';

        self::attempt_include($file_path, $data);
    }

    public static function attempt_include($file_path, $data=null) {

        if (file_exists($file_path)) {

            if (isset($data)) {
                extract($data);
            }

            require_once($file_path);
        } else {
            throw new Exception('模板不存在: '.$file_path);
        }
    }
}